require(["config"], function() {
	require(["jquery", "template", "cookie", "header"], function($, template) {
		function List() {
			this.renderList();
			this.renderRightList();
			this.addListener();
			this.products = null; // 保存购物车的商品数组结构

		}

		List.prototype = {
			constructor: List,
			// 渲染列表数据
			renderList: function() {
				$.ajax("http://rap2api.taobao.org/app/mock/94517/api/list")
					.done(function(data) {
						// 待渲染的数据
						var data = {
							list: data.res_body.list
						};

						/*	var lines = Math.ceil(data.list.length / 3);
						console.log(lines);
*/
						// 渲染
						var html = template("goods-items", data);
						$(".max_gallery_grid").prepend(html);
					});
			},
			renderRightList() {
				$.ajax("http://rap2api.taobao.org/app/mock/94517/api/list_right")
					.done(data => {
						var data = {
							list: data.res_body.list
						};
						//渲染
						var html = template("good_rightList", data);
						$(".list_right").html(html);
					});
			},
			//添加事件监听
			addListener() {
				$(".max_gallery_grid").on("click", ".decrement,.increment", $.proxy(this.decIncHandler, this));
				$(".max_gallery_grid").on("click", ".add_to_cart", $.proxy(this.loadCart, this));
			},
			//加载购物车数据
			loadCart(e) {
				var src = e.target,
					_parent = $(src).parents(".goods-item"),
					id = $(_parent).find(".good_id").val();
				var currPro = {
					id,
					title: _parent.find(".good_title").text(),
					img: _parent.find(".good_img").find("img").attr("src"),
					price: Number(_parent.find(".good_price").text()),
					amount: Number(_parent.find(".num").val())
				};
//				console.log(currPro.img)
				// 配置 cookie 插件自动转换 JS 与 JSON
				$.cookie.json = true;
				// 读取cookie中保存的购物车
				var products = this.products = $.cookie("cart") || [];

				//如果存在
				var has = products.some((prod) => {
					if(prod.id === currPro.id) {
						prod.amount += Number(_parent.find(".num").val());
						console.log(_parent.find(".num").val())
						return true;
					}
					return false;
				});
				if(!has)
					products.push(currPro);
				//保存到cookie
				$.cookie("cart", this.products, {
					expires: 2,
					path: "/"
				});
			},
			//数量加减
			decIncHandler(event) {
				var src = event.target;
				//				console.log($(event.data).html());
				var _num = $(src).parent().siblings(".num").val();
				//点击+/-改变数量
				if($(src).is(".decrement")) {
					if(_num <= 1)
						return;
					_num--;
				} else {
					_num++;
				}
				$(src).parent().siblings(".num").val(_num);
			}
		}
		new List();
	});
});